package com.example.installtest.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.installtest.BuildConfig;
import com.example.installtest.R;
import com.example.installtest.util.SilentInstall;

import java.io.File;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 仿360手机助手秒装和智能安装功能的主Activity。
 * 原文地址：http://blog.csdn.net/guolin_blog/article/details/47803149
 * @author guolin
 * @since 2015/12/7
 */
public class MainActivity extends AppCompatActivity {

    TextView apkPathText;

    String apkPath;

    TextView apkPathText1;

    String apkPath1;

    boolean startInstall=false;

    Queue<String> apkPaths=new ArrayBlockingQueue<String>(10);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        apkPathText = (TextView) findViewById(R.id.apkPathText);
        apkPathText1=findViewById(R.id.apkPathText1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            apkPath = data.getStringExtra("apk_path");
            apkPathText.setText(apkPath);
            apkPaths.add(apkPath);
        }
        if(requestCode==1&&resultCode==RESULT_OK){
            apkPath1=data.getStringExtra("apk_path");
            apkPathText1.setText(apkPath1);
            apkPaths.add(apkPath);
        }
    }

    /**
     * 选择安装包
     * @param view
     */
    public void onChooseApkFile(View view) {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0);
        }else{
            Intent intent = new Intent(this, FileExplorerActivity.class);
            startActivityForResult(intent, 0);
        }
    }

    /**
     * 选择第二个安装包
     * @param view
     */
    public void onChooseApkFile1(View view) {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }else{
            Intent intent = new Intent(this, FileExplorerActivity.class);
            startActivityForResult(intent, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    Intent intent = new Intent(this, FileExplorerActivity.class);
                    startActivityForResult(intent, 0);
                }else{
                    Toast.makeText(this, "您拒绝该权限将无法访问手机存储卡", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    /**
     * 静默安装
     * @param view
     */
    public void onSilentInstall(View view) {
        if (!isRoot()) {
            Toast.makeText(this, "没有ROOT权限，不能使用秒装", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(apkPath)) {
            Toast.makeText(this, "请选择安装包！", Toast.LENGTH_SHORT).show();
            return;
        }
        final Button button = (Button) view;
        button.setText("安装中");
        new Thread(new Runnable() {
            @Override
            public void run() {
                SilentInstall installHelper = new SilentInstall();
                final boolean result = installHelper.install(apkPath);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result) {
                            Toast.makeText(MainActivity.this, "安装成功！", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "安装失败！", Toast.LENGTH_SHORT).show();
                        }
                        button.setText("秒装");
                    }
                });
            }
        }).start();
    }

    /**
     * 打开无障碍通道
     * @param view
     */
    public void onForwardToAccessibility(View view) {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        startActivity(intent);
    }

    /**
     * 智能安装
     * @param view
     */
    public void onSmartInstall(View view) {
        startInstall=true;
        installApk();
    }

    private void installApk(){
        String apkPath= apkPaths.poll();
        startInstall=apkPaths.size()>0;
        if(TextUtils.isEmpty(apkPath)){
            Toast.makeText(this, "请选择安装包！", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent=new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri= FileProvider.getUriForFile
                    (this, BuildConfig.APPLICATION_ID+".fileProvider",new File(apkPath));
            Log.i("MainActivity", "contentUri: "+contentUri.getPath());
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        }else{
            Intent localIntent = new Intent(Intent.ACTION_VIEW);
            localIntent.setDataAndType(Uri.fromFile(new File(apkPath)),
                    "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(startInstall)
            installApk();
    }

    /**
     * 判断手机是否拥有Root权限。
     * @return 有root权限返回true，否则返回false。
     */
    public boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }
}
